import React , { Component } from "react";
import { Layout, ConfigProvider, Menu } from "antd";
import Media from 'react-media';
import Header from "./Header";
import Footer from "./Footer";
import logo from '../assets/yay.jpg';
import SiderMenu from '@/components/SiderMenu';
import menuJson from "@/menu"
import styles from './BasicLayout.less';
import { connect } from "dva";
import { isEmpty, isObject, cloneDeep} from "lodash-es"
import { setStorage, removeStorage } from '@/utils/utils';
import ModalComp  from "@/components/ModalItem/ModalComp"


const { Content, } = Layout;
class BasicLayout extends Component {

  constructor(props) {
    super(props);
    this.state = {
      iframeVisible: false, // iframe 弹框是否弹出
      iframeLoading: false, // iframe 弹框是否 loading
      iframeSetting: {
        title:'', // iframe 弹框的 title
        url:'', // iframe 的 src
      },
      iframeH : 400,
    };
    this.dealMenuJson();
    // 将 dispatch 方法放到当前 window 中，使得在任何地方都可以 dispatch(action)
    window.dvaDispatch = this.props.dispatch;
  }

  componentDidMount() {

  }

  componentDidUpdate(prevProps, prevState, snapshot) {

    //  如果 登录过期， 弹出 iframe 用于重新登陆
    if( false === prevProps.loginTimeout && this.props.loginTimeout){
      this.showIframe({
        title: '',
        url: `${window.location.origin}${window.location.pathname}#/user`,
      }, 'LOGIN');
    }else if(true === prevProps.loginTimeout && !this.props.loginTimeout){
      // 关闭弹窗
      this.hideIframe();

      //刷新应用状态数据 state
      this.props.dispatch({
        type:"global/afterLogin"
      })
    }
  }
  iframeLoadingTimer = null;
  /**
   * 打开弹窗 iframe
   * @returns {{paddingLeft: string}|null}
   */
  showIframe(iframeSetting,iframeApp){
    setStorage("IFRAME_APP",iframeApp);
    this.setState({
      ...iframeSetting,
      iframeVisible: true,
      iframeLoading: true,
    });
    // iframe 的 loading 效果
    if (this.iframeLoadingTimer) clearTimeout(this.iframeLoadingTimer);
    this.iframeLoadingTimer = setTimeout(() => {
      this.setState({ iframeLoading: false });
    }, 2000);
  }
  hideIframe(){
    removeStorage('SHOWING_TIMEOUT');
    removeStorage('IFRAME_APP');
    this.setState({ iframeVisible: false, iframeSetting: {} });
  }
  getLayoutStyle = () => {
        const { fixSiderbar, isMobile, collapsed, layout, siderWidth } = this.props;
        if (fixSiderbar && layout !== 'topmenu' && !isMobile) {
          return {
            paddingLeft: `${siderWidth}px`,
          };
        }
        return null;
      };
  /**
   * 过滤菜单权限
   */
  dealMenuJson(){
    this.menuJson = menuJson;
    const userInfo = this.props.userInfo || {};
    const userAuthResObj = userInfo.resources;
    if (!isEmpty(userAuthResObj) && isObject(userAuthResObj)) {
      // 遍历菜单，判断当前用户是否拥有菜单权限
      const menuArr = cloneDeep(menuJson.slice(1));
      // dealAuthMenu(menuArr, userAuthResObj);
      this.menuJson = this.menuJson.concat(menuArr);
    }
  }

   //开启/隐藏sider菜单
   handleMenuCollapse = collapsed => {
    const { dispatch } = this.props;
    dispatch({
      type: 'global/changeLayoutCollapsed',
      payload: collapsed,
    });
  };
    render(){
      const {children,isMobile, navTheme, layout:PropsLayout  } = this.props;
      const contentStyle = {};
      const isTop = PropsLayout === 'topmenu';
        const layout = (
          <Layout>
            {
              isMobile ? null : <SiderMenu
                logo={logo}
                theme={navTheme}
                menuData={this.menuJson}
                onCollapse={this.handleMenuCollapse}
                isMobile={isMobile}
                width={200}
                {...this.props}
              />
            }
              <Layout
                className={styles['layout-right']}
                style={{
                  ...this.getLayoutStyle(),
                  minHeight:"100vh"
                }}
                >
                <Header
                logo={logo}
                handleMenuCollapse={this.handleMenuCollapse.bind(this)}
                {...this.props}
                />
                <Content className={styles.content} style={contentStyle}>
                  {children}
                  {/*<Button onClick={() => {*/}
                  {/*  this.showIframe({*/}
                  {/*    title: '登录账号',*/}
                  {/*    url: `${window.location.origin}${window.location.pathname}#/user`,*/}
                  {/*  }, 'LOGIN');*/}
                  {/*}}>测试iframe</Button>*/}
                </Content>
                <Footer/>
              </Layout>
            </Layout>
        );
      let drawerWidth = 400;
        return (
            <ConfigProvider>
                <React.Fragment>
                    {layout}
                  {
                    // iframe弹窗
                    this.state.iframeVisible && (
                      <ModalComp
                      title={this.state.iframeSetting.title}
                      width={drawerWidth}
                      visible={this.state.iframeVisible}
                      destroyOnClose={true}
                      bodyStyle={{ padding: 0, background: '#ffffff' }}
                      footer={null}
                      loading={this.state.iframeLoading}
                      >
                        {
                          this.state.iframeSetting.url && (
                            <iframe className={styles.iframe} scrolling={'no'}
                                    style={{ height: this.state.iframeH }}
                                    src={this.state.iframeSetting.url}
                            />
                          )
                        }
                      </ModalComp>
                    )
                  }
                </React.Fragment>
            </ConfigProvider>
        )
    }
}
export default connect(({setting, global:{collapsed, siderWidth}})=>({
  collapsed,
  siderWidth,
  layout: setting.layout,
  ...setting,
}))(props => (
  <Media query="(max-width: 599px)">
    {isMobile => <BasicLayout {...props} isMobile={isMobile}/>}
  </Media>
));
